package top.xcxdl.rural.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.util.concurrent.AtomicDouble;
import lombok.extern.log4j.Log4j2;
import top.xcxdl.rural.entity.*;
import top.xcxdl.rural.mapper.*;
import top.xcxdl.rural.service.IRuralCourseService;
import top.xcxdl.rural.service.IRuralCourseUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.xcxdl.rural.service.IRuralQuestionService;
import top.xcxdl.rural.utils.ImageAddress;
import top.xcxdl.rural.utils.JWTUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Ding
 * @since 2022-05-22
 */
@Log4j2
@Service
public class RuralCourseUserServiceImpl extends ServiceImpl<RuralCourseUserMapper, RuralCourseUser> implements IRuralCourseUserService {

    @Resource
    private RuralCourseMapper courseMapper;

    @Resource
    private RuralQuestionMapper questionMapper;

    @Resource
    private RuralExamQuestionMapper examQuestionMapper;

    @Resource
    private RuralExaminationServiceImpl examinationService;

    @Override
    public int joinCourse(RuralCourseUser pojo) {
        if (pojo.getIsJoin() == 1) {
            //报课
            pojo.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000));
            pojo.setUpdateTime(String.valueOf(System.currentTimeMillis() / 1000));
            pojo.setIsPass(0);
            log.info("用户{}（ID为{}）报名了课程（ID为{}）", JWTUtils.getAuthorName(),JWTUtils.getAuthorId(),pojo.getCourseId());
            return baseMapper.insert(pojo);
        } else {
            //退课
            QueryWrapper<RuralCourseUser> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", pojo.getUserId());
            wrapper.eq("course_id", pojo.getCourseId());
            log.info("用户{}（ID为{}）退出了课程（ID为{}）", JWTUtils.getAuthorName(),JWTUtils.getAuthorId(),pojo.getCourseId());
            return baseMapper.delete(wrapper);
        }
    }

    @Override
    public boolean isExists(RuralCourseUser pojo) {
        QueryWrapper<RuralCourseUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", pojo.getUserId());
        wrapper.eq("course_id", pojo.getCourseId());
        return baseMapper.selectOne(wrapper) != null;
    }

    @Override
    public RuralCourseUser getByCourseAndUser(RuralCourseUser pojo) {
        QueryWrapper<RuralCourseUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", pojo.getUserId());
        wrapper.eq("course_id", pojo.getCourseId());
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public int toInsert(RuralCourseUser pojo) {
        return baseMapper.insert(pojo);
    }

    @Override
    public void automaticReview(RuralCourseUser courseUser) {
        //1.业务层根据实体中courseId查询rural_course表中的resource_id即examId
        Integer examId = courseMapper.getById(courseUser.getCourseId()).getCourseResource();
        //2.根据examId查询rural_examination表获取exam实体 -> 总分和通过分数
        RuralExamination exam = examinationService.getById(examId);
        Double totalScore = Double.parseDouble(String.valueOf(exam.getExamTotalScore()));
        Double passScore = Double.parseDouble(String.valueOf(exam.getExamPassScore()));
        //3.然后根据examId查询rural_exam_question表中对应的question的ids
        List<Integer> questionIds = examQuestionMapper.getIdsByExamId(examId);
        //4.然后根据questionIds查询rural_question表中对应的questions，罗列出想要的数据如正确答案
        QueryWrapper<RuralQuestion> wrapper = new QueryWrapper<>();
        wrapper.in("question_id", questionIds);
        List<RuralQuestion> list = questionMapper.selectList(wrapper);
        //创建并复制用户传来的userAnswerBody作为提交答案
        JSONObject finalUserAnswer = courseUser.getUserAnswerBody();
        //初始化得分
        final AtomicDouble score = new AtomicDouble(0.0);
        list.forEach(question -> {
            //字符串转json
            question.setQuestionOptionsBody(JSONArray.parseObject(question.getQuestionOptions(), JSONArray.class));
            question.setQuestionCorrectBody(JSONArray.parseObject(question.getQuestionCorrect(), JSONArray.class));
            if (finalUserAnswer != null && finalUserAnswer.containsKey(String.valueOf(question.getQuestionId()))) {
                //用户作答该题了
                //获取用户的答案
                JSONArray userAnswerBody = finalUserAnswer.getJSONArray(String.valueOf(question.getQuestionId()));
                //获取正确答案
                JSONArray correctAnswerBody = question.getQuestionCorrectBody();
                //获取正确答案数量
                int correctAnswerCount = correctAnswerBody.size();
                final AtomicInteger usercorrectAnswerCount = new AtomicInteger(0);
                correctAnswerBody.forEach(correctAnswer -> {
                    userAnswerBody.forEach(answer -> {
                        if (correctAnswer.equals(answer)) {
                            usercorrectAnswerCount.set(usercorrectAnswerCount.get() + 1);
                        }
                    });
                });
                question.setUserAnswerBody(userAnswerBody);
                //判断用户的答案是否正确
                if (usercorrectAnswerCount.get() == correctAnswerCount && userAnswerBody.size() == correctAnswerCount) {
                    question.setRight(true);
                    score.set(score.get() + Double.parseDouble(question.getQuestionScore()));
                } else {
                    question.setRight(false);
                    question.setQuestionCorrectBody(null);
                }
            } else {
                question.setQuestionCorrectBody(null);
            }
            question.setQuestionOptions(null);
            question.setQuestionCorrect(null);
        });
        //获取用户的得分
        courseUser.setUserScore(score.get());
        //根据分数设置本次考试是否通过
        courseUser.setIsPass(courseUser.getUserScore() >= passScore ?
                RuralCourseUser.PassCode.PASS :
                RuralCourseUser.PassCode.FAIL);
        //转储用户答案为String
        courseUser.setAnswer(JSONObject.toJSONString(courseUser.getUserAnswerBody()));
        //设置通过分、总分
        courseUser.setPassScore(passScore);
        courseUser.setTotalScore(totalScore);
        //设置更新时间
        courseUser.setUpdateTime(String.valueOf(System.currentTimeMillis() / 1000));
        //持久化（根据userId和courseId双重主键唯一性，查id再改多少脱裤子放屁了）
        QueryWrapper<RuralCourseUser> updateWrapper = new QueryWrapper<>();
        updateWrapper.eq("user_id", courseUser.getUserId());
        updateWrapper.eq("course_id", courseUser.getCourseId());
        baseMapper.update(courseUser, updateWrapper);
    }

}
